<template>
  <div id="mapPop">
    <el-dialog
      title="提示窗口"
      :visible.sync="dialogVisible"
      width="80vw"
      height="80vh"
      :before-close="handleClose"
      class="outWindow"
    >
      <div class="container">
        <div class="search-box">
          <!-- <input v-model="searchKey" type="search" id="search" />
          <button @click="searchByHand">搜索</button> -->
          <div class="tip-box" id="searchTip"></div>
          <el-input
            id="search"
            placeholder="请输入内容"
            class="input-with-select"
            v-model="searchKey"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchByHand"
            ></el-button>
          </el-input>
        </div>
        <!--
          amap-manager： 地图管理对象
          vid：地图容器节点的ID
          zooms： 地图显示的缩放级别范围，在PC上，默认范围[3,18]，取值范围[3-18]；在移动设备上，默认范围[3-19]，取值范围[3-19]
          center： 地图中心点坐标值
          plugin：地图使用的插件
          events： 事件
        -->
        <el-amap
          class="amap-box"
          :amap-manager="amapManager"
          :vid="'amap-vue'"
          :zoom="zoom"
          :plugin="plugin"
          :center="center"
          :events="events"
          v-if="reloadFlag"
        >
          <!-- 标记 -->
          <el-amap-marker
            v-for="(marker, index) in markers"
            :position="marker"
            :key="index"
          ></el-amap-marker>
        </el-amap>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { AMapManager, lazyAMapApiLoaderInstance } from 'vue-amap'
import qs from 'qs'
let amapManager = new AMapManager()

export default {
  name: 'mapPop',
  components: { qs },
  props: {
    dialogVisible: Boolean,
    city: Object
  },
  data () {
    let self = this
    return {
      address: null,
      searchKey: '',
      amapManager,
      markers: [],
      searchOption: {
        city: '全国',
        citylimit: true
      },
      center: [120.15507, 30.274084],
      zoom: 17,
      lng: 0,
      lat: 0,
      loaded: false,
      poiPicker: null,
      map: '',
      events: {
        init () {
          lazyAMapApiLoaderInstance.load().then(() => {
            self.initSearch()
          })
        },
        // 点击获取地址的数据
        click (e) {
          self.markers = []
          let { lng, lat } = e.lnglat
          self.lng = lng
          self.lat = lat
          self.center = [lng, lat]
          self.markers.push([lng, lat])
          // 这里通过高德 SDK 完成。
          let geocoder
          AMap.plugin(['AMap.Geocoder'], () => {
            geocoder = new AMap.Geocoder({
              radius: 1000,
              extensions: 'all'
            })
          })
          geocoder.getAddress([lng, lat], (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                console.log(result.regeocode.formattedAddress) // 控制台打印地址
                self.address = result.regeocode.formattedAddress
                self.searchKey = result.regeocode.formattedAddress
                self.$nextTick()
              }
            }
          })
        }
      },
      // 一些工具插件
      plugin: [
        {
          pName: 'Geocoder',
          events: {
            init (o) {
              // console.log("一些工具插件--地址"+o.getAddress())
            }
          }
        },
        {
          // 定位
          pName: 'Geolocation',
          events: {
            init (o) {
              // o是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  // 设置经度
                  self.lng = result.position.lng
                  // 设置维度
                  self.lat = result.position.lat
                  // 设置坐标
                  self.center = [self.lng, self.lat]
                  self.markers.push([self.lng, self.lat])
                  // load
                  self.loaded = true
                  // 页面渲染好后
                  self.$nextTick()
                }
              })
            }
          }
        },
        {
          // 工具栏
          pName: 'ToolBar',
          events: {
            init (instance) {
              // console.log("工具栏:"+instance);
            }
          }
        },
        {
          // 鹰眼
          pName: 'OverView',
          events: {
            init (instance) {
              // console.log("鹰眼:"+instance);
            }
          }
        },
        {
          // 地图类型
          pName: 'MapType',
          defaultType: 0,
          events: {
            init (instance) {
              // console.log("地图类型:"+instance);
            }
          }
        },
        {
          // 搜索
          pName: 'PlaceSearch',
          events: {
            init (instance) {
              // console.log("搜索:"+instance)
            }
          }
        }
      ],
      position: [],
      reloadFlag: true
    }
  },
  watch: {
    dialogVisible: function (val) {
      this.$emit('func', this.dialogVisible)
    },
    city: function (val) {
      this.getCityCode()
      this.reloadOfPart()
      lazyAMapApiLoaderInstance.load().then(() => {
        this.map = new AMap.Map('amapContainer', {
          center: this.center
        })
      })
      this.reloadOfPart()
    }
  },
  methods: {
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    initSearch () {
      // AMapUI.setDomLibrary($)
      let map = this.amapManager.getMap()
      AMapUI.loadUI(['misc/PoiPicker'], PoiPicker => {
        let poiPicker = new PoiPicker({
          input: 'search',
          placeSearchOptions: {
            map: map,
            pageSize: 10
          },
          suggestContainer: 'searchTip',
          searchResultsContainer: 'searchTip'
        })
        this.poiPicker = poiPicker
        // console.log(poiPicker)
        // 监听poi选中信息
        poiPicker.on('poiPicked', poiResult => {
          console.log(poiResult)
          let source = poiResult.source
          let poi = poiResult.item
          if (source !== 'search') {
            poiPicker.searchByKeyword(poi.name)
          } else {
            poiPicker.clearSearchResults()
            this.markers = []
            let lng = poi.location.lng
            let lat = poi.location.lat
            let address = poi.cityname + poi.adname + poi.name
            this.center = [lng, lat]
            this.markers.push([lng, lat])
            this.lng = lng
            this.lat = lat
            this.address = address
            this.searchKey = address
          }
        })
      })
    },
    searchByHand () {
      if (this.searchKey !== '') {
        console.log(this.poiPicker)
        this.poiPicker.searchByKeyword(this.searchKey)
      }
    },
    getCityCode () {
      // let url = 'http://localhost:8444/city_code?' + 'city='
      let url = 'https://restapi.amap.com/v3/geocode/geo?'
      // let parems = this.city.name
      let params = {
        key: '142566f6064108a30b1e26b72cc901a2',
        address: this.city.city
      }
      this.$axios.get(url + qs.stringify(params)).then(res => {
        if (res) {
          let result = res.data
          let temp = result.geocodes[0].location.split(',')
          this.center[0] = parseFloat(temp[0])
          this.center[1] = parseFloat(temp[1])
          // this.city.name = result.geocodes[0].city
          // this.city.province = result.geocodes[0].province
          // this.city.code = result.geocodes[0].adcode
          console.log(this.city)
          this.reloadOfPart()
        }
      })
    },
    reloadOfPart () {
      this.reloadFlag = false
      this.$nextTick(() => {
        this.reloadFlag = true
      })
    }
  },
  mounted: function () {
    console.log(this.searchKey)
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 70vw;
  height: 60vh;
  position: relative;
  left: 50%;
  top: 50%;
  transform: translate3d(-50%, 0, 0);
  border: 1px solid #999;
}
.search-box {
  position: absolute;
  z-index: 5;
  width: 40%;
  left: 5%;
  top: 10px;
  height: 30px;
}
.search-box input {
  float: left;
  width: 80%;
  height: 100%;
  border: 1px solid #30ccc1;
  padding: 0 8px;
  outline: none;
}
.search-box button {
  float: left;
  width: 30%;
  height: 100%;
  background: #30ccc1;
  border: 1px solid #30ccc1;
  color: #fff;
  outline: none;
}
.tip-box {
  width: 100%;
  max-height: 260px;
  position: absolute;
  top: 30px;
  overflow-y: auto;
  background-color: #fff;
}
</style>
